import moment from "moment";

export class Utility {

    static isTrue(input: boolean | undefined | null): boolean {
        return typeof (input) == "boolean" && input
    }

    static isFalse(input: boolean | undefined | null): boolean {
        return typeof (input) == "boolean" && input === false
    }

    static isDateTime(input: string | undefined | null): boolean {
        if (typeof input === "string") {
            return moment(input, "YYYY-M-D", true).isValid()
                || moment(input, "YYYY-M-D H:m", true).isValid()
                || moment(input, "YYYY-M-D H:m:s", true).isValid()
        }
        return moment.isDate(input)
    }

    toJson<T>(clazz: T): T {
        return JSON.parse(JSON.stringify(clazz)) as T
    }

    static removeArrayByIndex<T>(array: T[], index: number): T[] {
        if (index > -1 && index < array.length) {
            return array.splice(index, 1);
        }
        return array
    }

    static removeArrayByItem<T>(array: T[], item: T): T[] {
        const index = array.indexOf(item)
        return this.removeArrayByIndex(array, index)
    }

    /**
     * 集合中的特定元素前移1位
     * @param array
     * @param index
     */
    static upArrayByIndex<T>(array: T[], index: number): T[] {
        if (index < 1) {
            return array
        }
        if (array.length < 2) {
            return array;
        }
        return this.arrayMove(array, index, index - 1)
    }

    /**
     * 集合中的特定元素后移1位
     * @param array
     * @param index
     */
    static downArrayByIndex<T>(array: T[], index: number): T[] {
        if (index >= array.length - 1) {
            return array
        }
        if (array.length < 2) {
            return array;
        }
        return this.arrayMove(array, index, index + 1)
    }

    static arrayMove<T>(arr: T[], currentIndex: number, newIndex: number): T[] {
        if (newIndex >= arr.length) {
            var k = newIndex - arr.length + 1;
            while (k--) {
                arr.push(undefined as any);
            }
        }
        arr.splice(newIndex, 0, arr.splice(currentIndex, 1)[0]);
        return arr;
    }

    private static _debounce = new Array()
    /**
     * 延迟调用指定的方法(防抖动)
     * @param func
     * @param delay
     */
    static debounce(func: Function, delay: number = 500) {
        if (delay < 0) { delay = 10; }
        var hash = func.toString()
        var find: any | null = null;
        for (var i = 0; i < this._debounce.length; i++) {
            if (this._debounce[i].funcId === hash) {
                find = this._debounce[i];
                break;
            }
        }
        if (find === null) {
            find = {};
            this._debounce.push(find);
        } else {
            clearTimeout(find.taskId);
        }
        find.funcId = hash;
        find.taskId = setTimeout(func, delay);
    }


}